package com.cloudmind.filetransfer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cloudmind.filetransfer.CldUpdate.CldReceiver;

public class CldUsbMoniter {    
	private final static String TAG = "CldUsbMoniter";
	private Context context;
	private Handler handler = null;
	private CldUsbReceiver receiver;
	private IntentFilter filter;
	private boolean run = false;

	public static final int CLD_MSG_USB_MOUNTED = 100;
	public static final int CLD_MSG_USB_UNMOUNTED = 101;
	
	public CldUsbMoniter(Context context, Handler handler){
		this.context = context;
		this.handler = handler;

		receiver = new CldUsbReceiver();
		
		filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED); 
		filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); 
		filter.addDataScheme("file"); 
	}

	public void start(){
		Log.e(TAG, "start");   
		if(run == false){
			context.registerReceiver(receiver, filter,"android.permission.READ_EXTERNAL_STORAGE",null);
			run = true;
		}
	}

	public void stop(){
		Log.e(TAG, "stop"); 
		if(run == true){
			context.unregisterReceiver(receiver);
			run = false;
		}
	}
	
	class CldUsbReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG,"onReceive");
			String action = intent.getAction();
			String path = intent.getData().getPath();
			
			if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
				Log.e(TAG,"onReceive ACTION_MEDIA_MOUNTED path : " + path);
				Message m = new Message();
				m.setTarget(handler);
				m.what = CLD_MSG_USB_MOUNTED;
				Bundle strings = new Bundle();
				strings.putString("path", path);
				m.obj = strings;
				handler.sendMessage(m);
			}else if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED)){
				Log.e(TAG,"onReceive ACTION_MEDIA_UNMOUNTED path : " + path);
				Message m = new Message();
				m.setTarget(handler);
				m.what = CLD_MSG_USB_UNMOUNTED;
				Bundle strings = new Bundle();
				strings.putString("path", path);
				m.obj = strings;
				handler.sendMessage(m);
			} 
		}
	}
	
}